<?php

/**
 * @package Kpl
 * @author ava
 * @version $Id: Executor.php 225 2009-03-04 09:10:34Z code.ninjia $
 *
 */

class Executor
{
	// test svn commit
	const PARAM_NAMEVALUE_SEPARATOR = '=';

	protected $_params = array();
	protected $_env = array();
	protected $_lastExecutedCommand = null;
	protected $_lastExecutedStatus = null;
	protected $_lastExecutedOutput = null;
	
	public function execute($command, $noescape = false)
	{


		if(!empty($this->_env))
		{
			foreach($this->_env as $name => $value)
			putenv($name . self::PARAM_NAMEVALUE_SEPARATOR . $value);
		}


		$full_command = $this->generate($command, $noescape);

		exec($full_command, $output, $status);

		$result = array();
		foreach($output as $index => $line)
		$result[$index] = Util::iconvStorageToApp($line);

		$this->_lastExecutedCommand = $full_command;
		$this->_lastExecutedStatus = $status;
		$this->_lastExecutedOutput = $result;
		
		if ($this->getLastStatus() === 0) return true;
		else return false;
	}
	
	public function getLastStatus() {
		return $this->_lastExecutedStatus;
	}
	
	public function getLastOutput() {
		return $this->_lastExecutedOutput;
	}
	
	public function getLastCommand()
	{
		return  Util::iconvStorageToApp($this->_lastExecutedCommand);
	}
	
	public function getLastExport() {
		return trim( Util::iconvStorageToApp($this->_lastExportParams));
	}
	
	

	public function generate($command,$noescape = false) {
		if(!empty($this->_params))
		{
			$params = '';
			foreach($this->_params as $name => $value)
			{
				$params .= ' ' . $name;
				if(!is_null($value))
				{
					$params .= self::PARAM_NAMEVALUE_SEPARATOR;
					$params .= ($noescape) ? $value : escapeshellarg($value);
				}
			}
		}

		$command = ($noescape) ? $command : escapeshellcmd($command);
		return $command.$params;
		//return $command.$params." 1>>/tmp/ouput 2>>/tmp/errors";
		//return $command . $params." 2>/dev/null";
	}
	

	public function setEnv($name, $value)
	{
		if (strpos(trim($value),' ')) $value = "'".$value."'";
		
		$this->_env[$name] = $value;
		$this->_lastExportParams .= "export $name=$value &&\n";
		return $this;
	}


	public function setParam($name, $value = null)
	{
		$this->_params[$name] = $value;
		return $this;
	}

	public function getWorkingDirectory()
	{
		return getcwd();
	}
	
	public function setWorkingDirectory($dir)
	{
		if(is_dir($dir))
		{
			chdir($dir);
		}
			
		return $this;
	}

	public function reset()
	{
		$this->_params = array();
		$this->_env = array();
		$this->_lastExportParams = null;
		
		return $this;
	}
}
?>
